import { Form } from "@arco-design/web-react";
import { omit } from "lodash-es";
import { useEffect } from "react";

type Param<T> = {
  storageKey: string,
  ignoreFields?: (keyof T)[],
  initValue?: Partial<T>
}

export const useStorageForm = <T>({ storageKey, ignoreFields = [], initValue }: Param<T>) => {
  const [form] = Form.useForm<T>();

  useEffect(() => {
    const data = localStorage.getItem(storageKey);
    if (data) {
      form.setFieldsValue(JSON.parse(data));
    } else if (initValue) {
      form.setFieldsValue(initValue as any)
    }
  }, [])

  const saveForm = () => {
    const data = form.getFieldsValue();
    localStorage.setItem(storageKey, JSON.stringify(omit(data, ignoreFields)));
  };

  return {
    form,
    clearStorage: () => {
      localStorage.removeItem(storageKey);
    },
    saveForm,
  };
}